package com.road7.mina.customcodecfactory;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import com.road7.mina.pb.student.StudentMsgProto;
import com.road7.mina.pb.student.StudentMsgProto.StudentRspMsg;

/**
 * @Description :
 * @FileName: ProtobufStrictEncoder.java
 * @Author :WeiHui.Zhang
 * @Data : 2015年11月23日 下午8:24:20
 * @Version:V1.00
 */
public class ProtobufStrictEncoder extends ProtocolEncoderAdapter {

	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {

		StudentMsgProto.StudentRspMsg studentRspMsg = (StudentRspMsg) message;

		
		byte[] byteArray = studentRspMsg.toByteArray();// Student对象转为protobuf字节码

		int length = byteArray.length;

		IoBuffer buffer = IoBuffer.allocate(length + 4);//4字节的header
		buffer.putInt(length); // write header
		buffer.put(byteArray); // write body
		buffer.flip();
		out.write(buffer);
	}

}
